import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:my_flutter_test/models/utils.dart';

import '../models/briefItems.dart';
import '../models/itemInfo.dart';
import '../models/user.dart';
import 'package:dio/dio.dart';

var options = BaseOptions(baseUrl: 'http://localhost:3000');
var dio = Dio(options);

Future<void> requestRegister(String name, String pwd, Uint8List? img) async {
  // 注意用户可能不上传头像
  var resp = await dio.post('/user/register/',
      data: {
        'username': name,
        'password': pwd,
        'confirmedPassword': pwd,
        'img': img != null ? bytes2base64(img) : ''
      });
  // 返回的Json结构见User类
  var map = resp.data as Map<String, dynamic>;
  if (map['error_message'] == 'success') {
    return;
  } else {
    throw Exception();
  }
}

Future<User> requestLogin(String name, String pwd) async {
  var resp = await dio.post('/user/login/', data: {'username': name, 'password': pwd});
  String token = (resp.data as Map<String, dynamic>)['token'];
  print(token);
  dio.options.headers['Authorization'] = "Bearer $token";
  return User(name, pwd, token, Uint8List(0x0));
}


Future<BriefItems> mockSearchData(String keywords) async {
  return Future.delayed(const Duration(seconds: 2), () {
    return BriefItems(<BriefItem>[
      for (final i in List.generate(
          keywords.isNotEmpty ? keywords.length : 7, (x) => x))
        BriefItem(Uint8List.fromList([0x0]), "chick", "1919", i)
    ]);
  });
}
/// mock开始的都是生成模拟数据的测试方法
Future<ItemInfo> mockItemInfo(int id) async {
  return Future.delayed(const Duration(seconds: 1), () {
    return ItemInfo(
        Uint8List.fromList([]),
        "chick",
        "1919",
        810,
        "zyntm",
        "你干嘛",
        List<Comment>.generate(100, (index) =>
            Comment("Ayaya", "yarimasune", Uint8List.fromList([0x0]))));
  });
}

/// 获取物品的详细信息，用于显示物品的详细信息页面
/// 使用id查询
Future<ItemInfo> queryItemInfo(int id) async {
  var resp = await dio.get('/items', queryParameters: {'id': id});
  return ItemInfo.fromJson(resp.data as Map<String, dynamic>);
}

/// 根据关键词搜索物品，
/// 约定若关键词为空字符串，则返回所有物品
Future<BriefItems> queryItemByKeywords(String keyword) async {
  var resp = await dio.get('/items', queryParameters: {'keyword': keyword});
  return BriefItems.fromJson(resp.data as Map<String, dynamic>);
}

